﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sworm
{
    sealed class JoinMapper<TRoot>
    {
        private RecordTracker tracker = new RecordTracker();

        private readonly JoinResultSetDescription description;
        private readonly DataReader reader;

        public JoinMapper(JoinResultSetDescription description, DataReader reader)
        {
            this.description = description;
            this.reader = reader;
            description.Prepare(reader);
        }

        private Dictionary<JoinDefinition, object> currentInstances = new Dictionary<JoinDefinition, object>();

        public List<TRoot> Map()
        {
            var list = new List<TRoot>();

            while (reader.Reader.Read())
            {
                TRoot root = (TRoot)CreateObjectOrReturnExisting(description.Root, reader);
                if (list.Count == 0 || !object.Equals(list[list.Count - 1], root))
                {
                    list.Add(root);
                    currentInstances[description.Root] = root;
                }

                foreach (var join in description.JoinsExcludeRoot)
                {
                    object item = CreateObjectOrReturnExisting(join, reader);
                    currentInstances[join] = item;
                }

                foreach (var join in description.JoinsExcludeRoot)
                {
                    object destItem = currentInstances[join];
                    object sourceItem = currentInstances[join.Parent];
                    ApplyJoin(join.Relationship.SourceMember, sourceItem, destItem);
                    ApplyJoin(join.Relationship.DestinationMember, destItem, sourceItem);
                }
            }

            return list;
        }

        private static void ApplyJoin(Member member, object instance, object value)
        {
            if (member == null)
            {
                return;
            }
            if (!member.IsCollection)
            {
                if (instance != null && value != null)
                {
                    member.SetValue(instance, value);
                }
            }
            else
            {
                if (instance != null)
                {
                    member.EnsureCollectionInitialized(instance);
                }
                if (instance != null && value != null)
                {
                    member.AddToCollection(instance, value);
                }
            }
        }

        private object CreateObjectOrReturnExisting(JoinDefinition join, DataReader reader)
        {
            if(join.PrimaryKey == null)
            {
                throw new Exception("TODO");
            }

            var pk = join.PrimaryKey;
            object pkVal = reader.Reader[pk.ResultSetName];

            if (pkVal == DBNull.Value || pkVal == null)
            {
                return null;
            }

            object instance = tracker.TryGet(join.Table.ClassType, pkVal);
            if (instance != null)
            {
                return instance;
            }

            instance = join.Table.CreateInstance<object>();

            foreach (var column in join.Columns)
            {
                var accessor = new DbAccessor(reader.Reader, column.Index);
                column.Column.SetDbValue(instance, accessor);
            }

            tracker.Put(join.Table.ClassType, pkVal, instance);
            return instance;
        }
    }
}
